<template>
  <div class="list-container">
    <div class="list-toolbar">
      <el-date-picker
        type="month"
        class="w-110px"
        v-if="datePicker === 'show'"
        v-model="dateMonth"
        @focus="focusHandler"
        @change="changeHandler"
        :picker-options="pickerOptions"
      ></el-date-picker>
      <slot name="toolBar"></slot>
    </div>
    <button
      type="button"
      role="primary"
      circle
      class="el-icon-plus addBtn"
      size="medium"
      @click="editHandler(0, true)"
      v-show="!onAdd"
    ></button>
    <div
      v-loading="loading"
      class="list-group"
      :style="'height:' + listHeight"
    >
      <div v-show="!localDataList || !localDataList.list ||localDataList.list.length === 0" class="text-info text-c">
        {{ $t('common.noData') }}
      </div>
      <app-card shadow="hover" v-for="(item, index) in localDataList.list" :key="index">
        <el-form :model="item" class="l-h-1-6em" ref="form">
          <el-row>
            <el-col :xs="8" :sm="8" :md="6" :lg="5" :xl="3" name="list-left">
              <slot name="left" :item="item" :index="index"></slot>
            </el-col>
            <el-col
              :xs="11"
              :sm="11"
              :md="14"
              :lg="16"
              :xl="18"
              name="list-middle"
            >
              <slot name="middle" :item="item" :index="index"></slot>
            </el-col>
            <el-col
              :xs="5"
              :sm="5"
              :md="4"
              :lg="3"
              :xl="3"
              name="list-right"
              class="text-r"
            >
              <button
                type="button"
                role="text"
                @click="editHandler(index)"
                v-show="!item.inEdit"
                >{{ $t('common.edit') }}</button
              >
              <button
                type="button"
                role="text"
                @click="delHandler(index)"
                v-show="!item.inEdit"
                >{{ $t('common.del') }}</button
              >
              <button
                type="button"
                role="text"
                @click="saveHandler(index)"
                v-show="item.inEdit"
                >{{ $t('common.save') }}</button
              >
              <button
                type="button"
                role="text"
                @click="cancelHandler(index)"
                v-show="item.inEdit"
                >{{ $t('common.cancel') }}</button
              >
            </el-col>
          </el-row>
        </el-form>
      </app-card>
    </div>
  <confirm-box ref="confirmBox"></confirm-box>
  <paging  v-show="localDataList&&localDataList.list&&localDataList.list.length!==0"  :total="localDataList.count" :defaultSize="defaultSize" @page-handler="(limit,offset)=>$emit('page-handler',limit,offset)"></paging>
  </div>
</template>
<script>
import AppCard from '@/components/common/AppCard'
import { greaterThanEqualsAfter30Days } from '@/assets/utils/commonUtil'
import ConfirmBox from '@/components/common/ConfirmBox'
import Paging from '@/components/common/paging/Index'
const limit = 470
export default {
  data () {
    return {
      onAdd: false,
      dateMonth: this.dateModel,
      oldDateMonth: {},
      pickerOptions: { disabledDate: greaterThanEqualsAfter30Days },
      tempItem: {},
      localDataList: {}
    }
  },
  props: {
    defaultSize: { type: Number },
    count: { type: Number },
    dataList: {
      type: Object,
      required: true
    },
    datePicker: { type: String, default: 'hidden' },
    loading: { type: Boolean },
    prop: { type: String, required: true },
    dateModel: {},
    listHeight: { type: String, default: '100%' }
  },
  components: { AppCard, ConfirmBox, Paging },
  watch: {
    dataList () {
      this.localDataList = this.$props.dataList
      this.computeWidthClass()
    }
  },
  mounted () {
    const VueObj = this
    window.addEventListener('resize', () => {
      VueObj.computeWidthClass()
    })
  },
  updated () {
    this.computeWidthClass()
  },
  methods: {
    computeWidthClass () {
      this.replaceWidthClass(
        document.getElementsByName('list-left'),
        'el-col-xs-8',
        'el-col-xs-18'
      )
      this.replaceWidthClass(
        document.getElementsByName('list-middle'),
        'el-col-xs-12',
        'el-col-xs-18'
      )
      this.replaceWidthClass(
        document.getElementsByName('list-right'),
        'el-col-xs-4',
        'el-col-xs-6'
      )
    },
    replaceWidthClass (nodeList, greaterThanLimitwidth, lessThanLimitWidth) {
      const clientWidth = document.body.clientWidth
      nodeList.forEach(item => {
        let classList = item.getAttribute('class')
        if (clientWidth <= limit) {
          classList = classList.replace(
            greaterThanLimitwidth,
            lessThanLimitWidth
          )
        } else {
          classList = classList.replace(
            lessThanLimitWidth,
            greaterThanLimitwidth
          )
        }
        item.setAttribute('class', classList)
      })
    },
    addHandler () {
      this.onAdd = true
      this.localDataList.list.unshift({ inEdit: true })
      this.$emit('addHandler')
    },
    editHandler (index, isNew) {
      const filtered = this.localDataList.list.find(item => item.inEdit)
      if (filtered !== undefined) {
        this.$refs.confirmBox.confirm({
          title: this.$t('common.tips'),
          message: this.$t('common.editingTipsMessage'),
          type: 'warning'
        }).then(() => {
          const foundIndex = this.localDataList.list.findIndex(item => item.inEdit === true)
          const editIndex = this.onAdd ? index - 1 : index
          this.cancelHandler(foundIndex).then(() => {
            isNew ? this.addHandler() : this.editItem(editIndex)
          })
        })
      } else {
        isNew ? this.addHandler() : this.editItem(index)
      }
    },
    editItem (index) {
      this.tempItem = JSON.parse(JSON.stringify(this.localDataList.list[index]))
      this.$set(this.localDataList.list[index], 'inEdit', true)
      this.$emit('editHandler', index)
    },
    delHandler (index) {
      this.$refs.confirmBox.confirm({
        title: this.$t('common.tips'),
        message: '<span>' + this.$t('common.deleteRecordMessage1') + '<span class="color-warning">' + this.localDataList.list[index][this.prop] + '</span>' + this.$t('common.deleteRecordMessage2') + '</span>',
        type: 'warning'
      }).then(() => {
        if (!this.localDataList.list[index].id) {
          this.onAdd = false
        }
        this.$emit('delHandler', index)
      })
    },
    saveHandler (index) {
      if (!this.localDataList.list[index].id) {
        this.onAdd = false
      }
      this.$emit('saveHandler', index)
    },
    cancelHandler (index) {
      return new Promise((resolve, reject) => {
        try {
          if (!this.localDataList.list[index].id) {
            this.onAdd = false
            this.localDataList.list.splice(index, 1)
            resolve()
          } else {
            this.$set(this.localDataList.list, index, this.tempItem)
            resolve()
          }
        } catch (er) {
          reject(er)
        }
      })
    },
    focusHandler () {
      this.oldDateMonth = JSON.parse(JSON.stringify(this.dateMonth))
    },
    changeHandler () {
      if (this.localDataList.list.findIndex(item => item.inEdit) > -1) {
        this.$confirm(
          this.$t('common.changeListDateTips'),
          this.$t('common.tips'),
          {
            confirmButtonText: this.$t('common.confirm'),
            cancelButtonText: this.$t('common.cancel'),
            type: 'warning'
          }
        )
          .then(() => {
            this.$emit('update:dateModel', this.dateMonth)
            this.$emit('change')
          })
          .catch(() => {
            this.dateMonth = JSON.parse(JSON.stringify(this.oldDateMonth))
          })
      } else {
        this.$emit('update:dateModel', this.dateMonth)
        this.$emit('change')
      }
    }
  }
}
</script>
